<template>
  <div class="container">
    <div class="app-container">
      <el-tree
        :data="data"
        :props="defaultProps"
        :default-expand-all="true"
        :expand-on-click-node="false"
      >
        <template v-slot="{ data }">
          <el-row class="el-row" type="flex" justify="space-between">
            <el-col>{{ data.name }}</el-col>
            <el-col :span="4">
              <span class="tree-manager">{{ data.managerName }}</span>

              <!-- 下拉显示 -->
              <el-dropdown @command="handleCommand($event, data.id)">
                <span class="el-dropdown-link">
                  操作<i class="el-icon-arrow-down el-icon--right" />
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="add">添加子部门</el-dropdown-item>
                  <el-dropdown-item command="edit">编辑部门</el-dropdown-item>
                  <el-dropdown-item command="del">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-col>
          </el-row>
        </template>
      </el-tree>
    </div>
    <!-- 新增部门弹层 -->
    <addDeptVue
      ref="addDept"
      :show-dialog.sync="showDialog"
      :fa-id="faId"
      @updateForm="getDepartmentFn"
    />
  </div>
</template>
<script>
import { getDepartment, delDepartment } from '@/api/department'
import { transListToTreeData } from '@/utils'
import addDeptVue from './components/addDept.vue'
export default {
  name: 'Department',

  components: {
    addDeptVue
  },
  data() {
    return {
      showDialog: false, // 控制新增部门弹层
      faId: null, // 当前部门的id
      data: [],
      defaultProps: {
        label: 'name',
        children: 'children'
      }
    }
  },
  created() {
    this.getDepartmentFn()
  },
  methods: {
    // 获取组织架构的封装好的方法
    async getDepartmentFn() {
      const res = await getDepartment()
      // 递归树状列表
      const treeRes = transListToTreeData(res, 0)
      this.data = treeRes
      console.log(this.data)
    },
    // 下拉菜单点击事件
    handleCommand(command, id) {
      this.faId = id
      if (command === 'add') {
        this.showDialog = true
      } else if (command === 'edit') {
        this.showDialog = true
        this.$nextTick(() => {
          this.$refs.addDept.getDepartmentDetail()
        })
      } else {
        this.$confirm('确认删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          await delDepartment(id)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getDepartmentFn()
        })
      }
    }
  }
}
</script>
<style scoped>
.app-container {
  padding: 30px 120px;
  font-size: 16px;
}
.el-row {
  /* height: 50px; */
  width: 100%;
  /* line-height: 50px; */
}
.tree-manager {
  width: 70px;
  display: inline-block;
  margin-right: 30px;
}
</style>
